package com.kfm.validationdemo.advice;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 该类可以处理异常，并且方法的返回值直接返回给前端
 * json --> method
 * `@ControllerAdvice`
 */
@ControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * 该方法可以处理 NullPointerException 异常
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    public ModelAndView handlerNullPointException() {
        System.out.println("NullPointerException");
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error");
        mv.addObject("msg", "空指针异常");
        return mv;
    }

    /**
     * 该方法可以处理 MethodArgumentNotValidException 异常
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String handlerMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        System.out.println(ex.getBindingResult().getAllErrors());
        List<ObjectError> allErrors = ex.getBindingResult().getAllErrors();
        for (ObjectError allError : allErrors) {
            String message = allError.getDefaultMessage(); // 获取在实体类上配置的注解里面的message属性值
            System.out.println(message);
        }
        return "error";
    }
}
